<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/26
 * Time: 20:32
 */

namespace App\Game\Traits;


use Carbon\Carbon;
use App\Models\Inf\Player;
use App\Models\Def\MainGamePlat;

trait MgTrait
{
    //代理登录
    public function getApiToken()
    {
        $url = $this->gameUrl . '/lps/j_spring_security_check';
        $params = [
            'j_username' => $this->JUsername,
            'j_password' => $this->JPassword,
        ];
        $this->header = array_merge($this->header, ['Content-Type' => 'application/x-www-form-urlencoded']);
        $output = $this->request('POST', $url, $params, $this->header);
        $output = json_decode($output, true);

        if (array_key_exists('token', $output)) {
            return $output;
        }

    }

    //玩家登录
    public function getMemberToken($accountUserName)
    {
        $mainGamePlat = MainGamePlat::where('main_game_plat_name', $this->platName)->first();
        $player = Player::where([
                ['main_game_plats_id', '=', $mainGamePlat->id],
                ['username', '=', $accountUserName],
            ]
        )->first();

        $timestamp = Carbon::now('UTC')->format('Y-m-d H:i:s e');
        $this->header = array_merge($this->header, ['Content-Type' => 'application/xml']);
        $url = $this->gameUrl . '/member-api-web/member-api';
        $body = '<mbrapi-login-call 
                timestamp="' . $timestamp . '" 
                apiusername="apiadmin" 
                apipassword="apipassword" 
                username="' . $accountUserName . '" 
                password="' . $player->password . '" 
                ipaddress="' . config('game.pub.AddressIp') . '" 
                partnerId="88KIOSK" 
                currencyCode="CNY" 
                />';

        $params = [
            'body' => $body
        ];

        $output = $this->request('POST', $url, [], $this->header, $params);
        $output = $this->xmlToArray($output);
        if ($output['@attributes']['status'] == 0) {
            return $output['@attributes']['token'];
        }
    }

    //返回数据处理，合并投注和赢数据
    public function pareReturnData(array $items)
    {
        array_walk($items, function (&$item) {
            if ($item['transType'] == 'bet') {
                $item['win'] = 0;
            }
            if ($item['transType'] == 'win') {
                $item['win'] = $item['amnt'];
                $item['amnt'] = 0;
            }
        }
        );

        return $items;
    }


    public function apiDataParse(array $apiData, array $data)
    {
        $data = $this->usernamePre($data);
        return $data;
    }

    private function usernamePre(array $data)
    {
        if (array_key_exists('username', $data)) {
            $data['username'] = str_after($data['username'], $this->clearPre);
        }
        return $data;
    }


}